package cn.zjgsu.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.zjgsu.domain.TbCourse;
import cn.zjgsu.domain.TbStudent;
import cn.zjgsu.domain.TbTask;
import cn.zjgsu.domain.TbTeacher;
import cn.zjgsu.domain.TbUser;
import cn.zjgsu.exception.MyException;
import cn.zjgsu.service.ICourseService;
import cn.zjgsu.service.IStudentService;
import cn.zjgsu.service.ITaskService;
import cn.zjgsu.utils.Page;
import cn.zjgsu.utils.SHA1;

/**
 * 学生操作
 * @author 颜佳钦
 *
 */
@Controller
@RequestMapping("/student")
public class StudentController {
	@Resource
	private IStudentService studentService;
	@Resource
	private ITaskService taskService;
	@Resource
	private ICourseService courseService;
	
	
	
	
	
	
	
	@RequestMapping("/index")
	public String index(HttpSession session,HttpServletRequest req) {

		if (session.getAttribute("user") == null)
	       return "student/index";
		else
			return"student/index";
		
	}

	/**
	 * @author 颜佳钦
	 *获取教师列表并且跳转到管理员首页
	 */
	@RequestMapping("/studentInfo")
	public String getStudentInfo(HttpServletRequest request){
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		
		int fkUser =user.getId();
		TbStudent student = studentService.getStudentByFkUser(fkUser);
		request.setAttribute("student", student);

		return "student/studentInfo";	
	}
	
	
	/**
	 * @author 颜佳钦
	 *教师信息保存
	 */
	@RequestMapping(value = "/saveInfo", method = RequestMethod.POST)
	public String saveInfo(HttpServletRequest request, TbStudent student)throws Exception{
		String strMessage;
		try{
	
        studentService.updateStudent(student);
	
		strMessage = "<script type='text/javascript'>alert('保存成功！')</script>";
			
		request.setAttribute("message", strMessage);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('保存失败！')</script>";
			 request.setAttribute("message", strMessage);
			
		}
		return "forward:/student/studentInfo/";
	}
	
	
	
	/**
	 * @author 颜佳钦
	 *获取学生名字并跳转到密码修改页面
	 */
	@RequestMapping("/changePasswordUI")
	public String changePasswordUI(HttpServletRequest request){
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		
		int fkUser =user.getId();

		TbStudent  student =studentService .getStudentByFkUser(fkUser);
		
		request.getSession().setAttribute("student",student);

		return "student/changePassword";	
	}
	
	/**
	 * @author 颜佳钦
	 *获取学生名字并跳转到密码修改页面
	 */
	@RequestMapping(value ="/changePassword", method = RequestMethod.POST)
	public String changePassword(HttpServletRequest request)throws Exception{
		//TbUser user = (TbUser) request.getSession().getAttribute("user");
		String errorold;
		String errorChange;
		String strMessage;
	  
	   TbStudent  student =(TbStudent)request.getSession().getAttribute("student");
	   String oldPassword=student.getStudentPwd();
	   String inputOldPassword=request.getParameter("oldPassword");
	   String changePassword=request.getParameter("changePassword");
	   String changeRepassword=request.getParameter("changeRepassword");
	   String yy=SHA1.encrypt(inputOldPassword).trim();
	   try{
	   if(!oldPassword.equals(SHA1.encrypt(inputOldPassword).trim()))
	   {
		    errorold= "密码输入不正确";
		   
		   request.setAttribute("errorold",errorold);
	   }
	   else if (!changePassword.equals(changeRepassword))
	   {
		   errorChange= "两次输入的密码不一致";
		   request.setAttribute("errorChange", errorChange);
	   }
	   else{
		   
		int pkStudent =student.getPkStudent();
		
		studentService.changeStudentPassword(pkStudent,changePassword);
		
		strMessage = "<script type='text/javascript'>alert('修改成功！')</script>";
		
		request.setAttribute("message", strMessage);
		
	   }
	   }catch (Exception e) {
			
			 strMessage = "<script type='text/javascript'>alert('修改密码失败！')</script>";
			 request.setAttribute("message", strMessage);
			
		}

		return "forward:/student/changePasswordUI/";	
	}
	

	/**
	 * @author 颜佳钦
	 *获取教师个人任务列表并且跳转到个人日历页面
	 */
	@RequestMapping("/taskManage")
	public String getTaskList(HttpServletRequest request){
		String pageNow = request.getParameter("pageNow");
		Page page=null;
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();

		List<TbTask>  listAll=new ArrayList<TbTask>();
		int totalCount=studentService.getTaskCount(fkUser);

		if(totalCount!=0){
			if(pageNow!=null){
				page=new Page(totalCount,Integer.parseInt(pageNow));
				listAll=studentService.selectByPage(page.getStartPos(),page.getPageSize(),fkUser);
			}else{
				page=new Page(totalCount, 1);
			
				listAll=studentService.selectByPage(page.getStartPos(),page.getPageSize(),fkUser);
			}
		}
		request.setAttribute("page", page);
		request.setAttribute("listAll", listAll);

		return "student/taskManage/taskList";	
	}
	
	/**
	 * @author 颜佳钦
	 *教师个人日历添加
	 */
	@RequestMapping(value = "/taskManage/taskImport", method = RequestMethod.POST)
	public String taskImport(HttpServletRequest request, TbTask task)throws Exception{
		String strMessage;
		try{
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		task.setFkUser(fkUser);
		taskService.addTask(task);
		strMessage = "<script type='text/javascript'>alert('添加成功！')</script>";
			
		request.setAttribute("message", strMessage);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('添加失败！')</script>";
			 request.setAttribute("message", strMessage);
			
		}
		return "forward:/student/taskManage";
	}
	
	

	/**
	 * @author 颜佳钦
	 *学生个人日历添加
	 */
	@RequestMapping(value = "/taskManage/taskImportJs", method = RequestMethod.POST)
	@ResponseBody
	public String taskImportJs(HttpServletRequest request, TbTask task)throws Exception{
		String strMessage;
		try{
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		task.setFkUser(fkUser);

		taskService.addTask(task);
		strMessage = "<script type='text/javascript'>alert('添加成功！')</script>";
			
		request.setAttribute("message", strMessage);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('添加失败！')</script>";
			 request.setAttribute("message", strMessage);
			
		}
		return "ok";
	}
	
	/**
	 * @author 颜佳钦
	 *个人日历的删除
	 */
	@RequestMapping("/taskManage/deleteTask/{pkTask}")
	public String deleteTask(@PathVariable("pkTask") int pkTask,HttpServletRequest request)throws Exception{
		
		String strMessage;
		try{
			
			taskService.deleteTask(pkTask);
			 strMessage = "<script type='text/javascript'>alert('删除成功！')</script>";
				
				request.setAttribute("message", strMessage);
		}
		catch(Exception e){
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('删除失败！')</script>";
				
				request.setAttribute("message", strMessage);
			throw new MyException("删除失败");
		}
		
		return "forward:/student/taskManage";
	}
	
	
	
	
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取
	 */
	@RequestMapping("/courseListUI")
	public String courseListUI(HttpServletRequest request){
		String strMessage;
       TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		TbStudent student =studentService.getStudentByFkUser(fkUser);
		request.getSession().setAttribute("student", student);
		List<String> listAll=studentService.getYear(student.getPkStudent());
		if(listAll.isEmpty())
		{
			
		   strMessage = "<script type='text/javascript'>alert('暂时没有课程,请先添加课程！')</script>";
	       request.setAttribute("message", strMessage);
			
			
		}
		else{
		request.setAttribute("listAll", listAll);
		}
		return "student/courseManage/courseList";	
	}
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取相关课程信息
	 */
	
	@RequestMapping(value="/findCourseRecordByYear", method = RequestMethod.POST)
	public @ResponseBody String findCourseRecordByYear(@RequestParam String year,HttpServletRequest request){
		String strMessage;
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		TbStudent student=studentService.getStudentByFkUser(fkUser);

		if(year==null)
		{
			
		   strMessage = "<script type='text/javascript'>alert('暂时没有课程,请先添加课程!')</script>";
	       request.setAttribute("message", strMessage);
		  return null;	
		}
		else{
					
		List<TbCourse> listAll2=studentService.findCourseRecordByYear(student.getPkStudent(),year);	
	
		String data =JSONObject.toJSONString(listAll2);
		return  data;
		}
			
	}
	/**
	 * @author 颜佳钦
	 *课表文件的下载
	 */
	@RequestMapping("/courseManage/download")
	public String downloadCourse(@RequestParam("pkCourse") int pkCourse,HttpServletRequest request, HttpServletResponse response)throws Exception{
		
		    String strMessage;
	
			TbCourse course =courseService.findCourseById(pkCourse);
			
			 File thefile =new File(course.getCoursePointAddress());
			 
			 if(thefile.exists())
			 {
				    String fileName = course.getCoursePointName().toString(); // 文件的默认保存名
				    //解决文件名中文乱码问题
				    if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
				    	fileName = URLEncoder.encode(fileName, "UTF-8");  
				    } else {  
				    	fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");  
				    }  
			        // 读到流中
			        InputStream inStream = new FileInputStream(course.getCoursePointAddress());// 文件的存放路径
			        // 设置输出的格式
			        response.reset();
			        response.setContentType("bin");
			        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName+ "\"");
			        // 循环取出流中的数据
			        byte[] b = new byte[100];
			        int len;
			        try {
			            while ((len = inStream.read(b)) > 0)
			                response.getOutputStream().write(b, 0, len);
			            inStream.close();
			          }
			        catch(Exception e){
						// TODO Auto-generated catch block
						 strMessage = "<script type='text/javascript'>alert('下载失败！')</script>";
							
							request.setAttribute("message", strMessage);
						throw new MyException("下载失败");
					}
			 }
			  else
			        {
			        	
				  strMessage = "<script type='text/javascript'>alert('暂无文件上传，请先上传！')</script>";
					
					request.setAttribute("message", strMessage);	
			        	
			        	
			        	
			        }
		
		
		
		return "forward:/student/courseListUI";
	}
	
}
